/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Feb 14, 2012  3:38:29 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : jpa.service.promis.common
 * File Name : CompanyServices.java
 * TODO
 */
package jpa.service.promis.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;

import org.apache.log4j.Logger;

import promis.utility.CommonService;

import jpa.entitys.common.CommonEntity;
import jpa.entitys.promis.common.Company;
import jpa.entitys.promis.common.CostProject;
import jpa.service.common.JPAService;

/**
 * @author chatree
 *
 */
public class CompanyServices extends JPAService{
	
	private static final Logger log = Logger.getLogger(CompanyServices.class);

	public CompanyServices(EntityManager em) {
		super(em);
		// TODO Auto-generated constructor stub
	}


	public Company findById(String id) throws Exception {
		
		return super.ConvertToYoureObject(super.find(id, "Company.findById"));				
	}
	
	public Company findBySapCompany(String sapCompanyCode) throws Exception {
		
		Map<String,Object> mapWhereValue = new HashMap<String, Object>();
		mapWhereValue.put("sapCompanyCode", sapCompanyCode);
		List<Company> lst = super.ConvertToYoureObject(super.find("Company.findBySapCompany", mapWhereValue));
		
		if(lst != null && CommonService.getSize(lst) == 1)
			return lst.get(0);
		else 
			return null;
	}
	
	public Company InsertedOrUpdated(Company vlaue) throws Exception {
		Company obj = vlaue;
		try{		
			if(CommonService.IsNull(obj.getLastUpdOn()))
			{							
				super.inserted(obj);
			}else{
				super.updated(obj);
			}
		}catch(Exception e)
		{
			log.error(e);
			throw e;
		}
		return obj;
	}
	
	public List<Company> Inserted(List<Company> vlauelist) throws Exception {
		try{
			List<CommonEntity> common_lst = new ArrayList<CommonEntity>();			
			for(Company obj : vlauelist)
			{
				common_lst.add(obj);
			}
			
			if(CommonService.getSize(common_lst) > 0)
				super.inserted(common_lst);
			
		}catch(Exception e)
		{
			log.error(e);
			throw e;
		}
		return vlauelist;
	}
	
	public List<Company> Updated(List<Company> vlauelist) throws Exception {
		try{
			List<CommonEntity> common_lst = new ArrayList<CommonEntity>();			
			for(Company obj : vlauelist)
			{
				if(!CommonService.IsNull(obj.getLastUpdOn()))
				{					
					common_lst.add(obj);					
				}
			}
			
			if(CommonService.getSize(common_lst) > 0)
				super.updated(common_lst);
			
		}catch(Exception e)
		{
			log.error(e);
			throw e;
		}
		return vlauelist;
	}
}
